package com.yc.sole.common.filter;

import cn.hutool.core.text.CharSequenceUtil;
import com.yc.sole.framework.context.SecureContextHolder;
import com.yc.sole.framework.utils.ResponseUtil;
import com.yc.sole.common.constant.PubConstant;
import com.yc.sole.framework.web.BaseUserInfo;
import com.yc.sole.framework.web.SecurityAuthenticator;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;

/**
 * token过滤器
 *
 * @author yizuomin
 * @date 2022/11/19 5:55 PM
 **/
@Slf4j
@RequiredArgsConstructor
@WebFilter(urlPatterns = "/api/**")
@Order(2)
@Component
public class TokenFilter implements Filter {

    private final SecurityAuthenticator securityAuthenticator;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (null != servletRequest.getAttribute("executeTokenFilter")) {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            String requestURI = request.getRequestURI();
            String requestHeader = request.getHeader(PubConstant.TOKEN_HEADER);
            //请求头没有获取到
            if (CharSequenceUtil.isBlank(requestHeader)) {
                log.error("path：{}，token is empty！！！！！", requestURI);
                ResponseUtil.returnResponse(servletResponse, 403, "请登录");
            } else {
                BaseUserInfo userInfo = securityAuthenticator.getUserInfo(requestHeader);
                if (Objects.isNull(userInfo)) {
                    log.error("path：{}，login expire！！！！！", requestURI);
                    ResponseUtil.returnResponse(servletResponse, 101, "登录超时，请重新登录");
                } else {
                    try {
                        SecureContextHolder.setUserInfo(userInfo);
                        servletRequest.setAttribute("executeAuthorityFilter", true);
                        filterChain.doFilter(servletRequest, servletResponse);
                    } finally {
                        SecureContextHolder.removeUser();
                    }
                }
            }
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }
}
